package com.lt.integration.qywx.util;

import com.alibaba.fastjson.JSON;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

public class AuthUtil {

    public static JSONObject doGetJson(String url) throws Exception, IOException {
        JSONObject jsonObject = null;
        //初始化httpClient
        DefaultHttpClient client = new DefaultHttpClient();
        //用Get方式进行提交
        HttpGet httpGet = new HttpGet(url);
        //发送请求
        HttpResponse response = client.execute(httpGet);
        //获取数据
        HttpEntity entity = response.getEntity();
        //格式转换
        if (entity != null) {
            String result = EntityUtils.toString(entity,"UTF-8");
            jsonObject = JSON.parseObject(result, JSONObject.class);
//            jsonObject = JSONObject.fromObject(result);
        }
        //释放链接
        httpGet.releaseConnection();
        return jsonObject;
    }

    public static JSONObject doPostJson(String url, List<NameValuePair> params) throws Exception, IOException {
        JSONObject jsonObject = null;
        //初始化httpClient
        DefaultHttpClient client = new DefaultHttpClient();
        //用Post方式进行提交
        HttpPost httpPost = new HttpPost(url);
        //添加参数  设置编码
        httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
        //发送Post,并返回一个HttpResponse对象
        HttpResponse response = client.execute(httpPost);
        //获取数据
        HttpEntity entity = response.getEntity();
        //格式转换
        if (entity != null) {
            String result = EntityUtils.toString(entity,"UTF-8");
            jsonObject = JSON.parseObject(result, JSONObject.class);
//            jsonObject = JSONObject.fromObject(result);
        }
        //释放链接
        httpPost.releaseConnection();
        return jsonObject;
    }

    /**
     * 传统的POST/GET 请求方式
     * @param toURL
     * @param data
     * @return
     * @throws Exception
     */
    public static JSONObject requestServiceJson(String toURL, String data){
        JSONObject jsonObject = null;
        StringBuffer bs = new StringBuffer();
        try {
            URL sendUrl = new URL(toURL.trim());
            URLConnection connection = sendUrl.openConnection();
            connection.setConnectTimeout(30000);
            connection.setReadTimeout(30000);
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type","application/json；chert=UTF-8");
            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
            out.write(data);
            out.flush();
            out.close();
            connection.connect();
            InputStream is = connection.getInputStream();
            BufferedReader buffer = new BufferedReader(new InputStreamReader(is,"UTF-8"));

            String l = null;
            while ((l = buffer.readLine()) != null) {
                bs.append(l);
            }
            jsonObject = JSON.parseObject(bs.toString(), JSONObject.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

    public static JSONObject doPostJson(String toURL, String data) {
        JSONObject jsonObject =  null;
        try {
            //创建连接
            URL url = new URL(toURL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.connect();


            //POST请求
            // 当有数据需要提交时
            if (null != data) {
                OutputStream outputStream = connection.getOutputStream();
                // 注意编码格式，防止中文乱码
                outputStream.write(data.getBytes("UTF-8"));
                outputStream.close();
            }
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.writeBytes(data);
            out.flush();
            out.close();

            //读取响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String lines;
            StringBuffer sb = new StringBuffer("");
            while ((lines = reader.readLine()) != null) {
                lines = new String(lines.getBytes(), "utf-8");
                sb.append(lines);
            }
            System.out.println(sb);
            reader.close();
            // 断开连接
            connection.disconnect();
            jsonObject = JSON.parseObject(sb.toString(), JSONObject.class);
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return jsonObject;
    }
}
